﻿using Microsoft.Extensions.Logging;
using System.Net;
using Shielded.Gossip;
using System;
using System.Collections.Generic;
using ConsoleApp1;

namespace GossipCore
{
    public class Program
    {
        /*
        Dictionary<string, string> peer = new (StringComparer.InvariantCultureIgnoreCase)
         {
             {"A", "127.0.0.1:9901"},
             {"B", "127.0.0.1:9902"},
             {"C", "127.0.0.1:9903"},
         };
        protected static readonly Dictionary<string, IPEndPoint> _addresses = new ()
        {
            { "A", new IPEndPoint(IPAddress.Loopback, 2001) },
            { "B", new IPEndPoint(IPAddress.Loopback, 2002) },
            { "C", new IPEndPoint(IPAddress.Loopback, 2003) },
        };*/
        
        public static void Main(string[] args)
        {
            var (id, peers) = ArgsParser.ParseArgs(args);
            using var cluster = new HazeCluster(id, peers);
            cluster.Start();

            Console.WriteLine($"Node {id} started. Peers: {string.Join(", ", peers.Keys)}. Press Enter to exit...");
            
            //cluster.SyncAllTopicsFromPeers();
            

            var uid = Guid.NewGuid().ToString();
            var topic = cluster.GetTopic<string>("test");
            topic.Subscribe((message) =>
            {
                Console.WriteLine($"Received message: {message}");
            });
            topic.Publish("Hello, world!" + uid);
            
            //如果id是C则每隔5秒发个消息
            if (id == "C")
            {
                var timer = new System.Threading.Timer(_ =>
                {
                    var msg = $"定时消息 {Guid.NewGuid()}";
                    topic.Publish(msg);
                    Console.WriteLine($"[C] 定时发送: {msg}");
                }, null, 0, 5000);
            }

            Console.ReadLine();
        }
    }
}